import enum
import uuid
from datetime import datetime

from sqlalchemy import Column, DateTime, Enum, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class TaskStatus(enum.Enum):
    """任务状态枚举"""

    PENDING = "pending"  # 待处理
    PROCESSING = "processing"  # 处理中
    SUCCESS = "success"  # 成功
    FAILED = "failed"  # 失败
    CANCELLED = "cancelled"  # 已取消


class ExportTask(Base):  # type: ignore
    """导出任务模型"""

    __tablename__ = "export_tasks"

    id = Column(Integer, primary_key=True, autoincrement=True)
    task_id = Column(String(36), unique=True, nullable=False, default=lambda: str(uuid.uuid4()))
    task_name = Column(String(255), nullable=False)
    status = Column(Enum(TaskStatus), default=TaskStatus.PENDING, nullable=False)

    # 任务参数
    query_params = Column(Text, nullable=True)  # JSON格式的查询参数
    export_type = Column(String(50), nullable=False)  # 导出类型：csv, excel, json

    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    started_at = Column(DateTime, nullable=True)
    finished_at = Column(DateTime, nullable=True)

    # 结果信息
    result_file_path = Column(String(500), nullable=True)
    error_message = Column(Text, nullable=True)
    total_records = Column(Integer, default=0)
    processed_records = Column(Integer, default=0)

    def __repr__(self):
        return f"<ExportTask {self.task_id}: {self.status.value}>"

    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "task_id": self.task_id,
            "task_name": self.task_name,
            "status": self.status.value,
            "query_params": self.query_params,
            "export_type": self.export_type,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "started_at": self.started_at.isoformat() if self.started_at else None,
            "finished_at": self.finished_at.isoformat() if self.finished_at else None,
            "result_file_path": self.result_file_path,
            "error_message": self.error_message,
            "total_records": self.total_records,
            "processed_records": self.processed_records,
            "progress": self.processed_records / max(self.total_records, 1) * 100 if self.total_records > 0 else 0,
        }
